<script setup lang="ts">
import { ref, watch } from 'vue';
import type { QTableColumn } from 'quasar';
import { useQuasar } from 'quasar';
import { reqGetSkuListBySpuId } from '@/api/product/spu.ts';
import type { SkuInfo } from '@/api/product/type.ts';
import { quasarTableStyle } from '@/setting';

const { notify } = useQuasar();
// SKUList
const isShowSkuList = ref<boolean>(false);
const spuId = ref<number>();
function showSkuList(currentSpuId: number | undefined) {
  isShowSkuList.value = true;
  spuId.value = currentSpuId;
}
defineExpose({ showSkuList });
watch(spuId, () => {
  if (!isShowSkuList.value) return;
  // TODO: 获取SKU列表
  getSkuList();
});
// SKUList
const skuList = ref<SkuInfo[]>([]);
const loading = ref<boolean>(false);
const getSkuList = async () => {
  loading.value = true;
  try {
    const result = await reqGetSkuListBySpuId(spuId.value!);
    if (result.code === 200) {
      skuList.value = result.data;
    } else {
      throw new Error('SKU列表获取失败');
    }
  } catch (error: any) {
    notify({
      type: 'negative',
      message: error.message,
      position: 'top'
    });
  } finally {
    loading.value = false;
  }
};
// SKUTable
const columns: QTableColumn[] = [
  {
    name: 'skuName',
    label: 'SKU名称',
    field: 'skuName',
    align: 'left',
    style: 'width: 200px'
  },
  {
    name: 'price',
    label: 'SKU价格',
    field: 'price',
    format: val => `${val}元`,
    align: 'left'
  },
  {
    name: 'weight',
    label: 'SKU重量',
    field: 'weight',
    format: val => `${val}g`,
    align: 'left'
  },
  { name: 'skuDefaultImg', label: 'SKU图片', field: '', align: 'left' }
];
</script>

<template>
  <!-- code... -->
  <q-dialog v-model="isShowSkuList">
    <q-card>
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">SKU列表</div>
        <q-space />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>
      <q-card-section>
        <q-table
          :separator="quasarTableStyle"
          :columns="columns"
          :rows="skuList"
          row-key="id"
          wrap-cells
          :rows-per-page-options="[0]"
          :loading="loading"
          hide-pagination
        >
          <template #body-cell-skuDefaultImg="{ row }">
            <q-td>
              <q-img :src="row.skuDefaultImg" style="width: 80px"></q-img>
            </q-td>
          </template>
        </q-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped>
/* code... */
</style>
